<template>
  <div id="map" class="map" tabindex="0"></div>
</template>

<script>
import "ol/ol.css";
import Map from "ol/Map";
import View from "ol/View";
import TileLayer from "ol/layer/Tile";
import { Vector as VectorLayer } from "ol/layer";
import { Vector as VectorSource } from "ol/source";
import Feature from "ol/Feature";
import { Point } from "ol/geom";
import { fromLonLat } from "ol/proj";
import { Fill, Circle, Style } from "ol/style";
import XYZ from 'ol/source/XYZ';
import { defaults as defaultControls } from 'ol/control';
import { KeyObject, KeyObjectDetails } from "@/api/leftDetailList-society"
export default {
  name: "HelloWorld",
  data() {
    return {
      map: null,
      resPdata: [],//点位数据
    };
  },

  mounted() {
    this.initMap();
    this.getMap();
  },

  methods: {
    // 初始化地图
    initMap() {
      this.map = new Map({
        layers: [
          new TileLayer({
            // 创建一个使用Open Street Map地图源的瓦片图层
            source: new XYZ({
              url: "https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}",
              wrapX: false
            })
          }),
        ],
        target: "map",
        view: new View({
          zoom: 3.8, // 缩放
          // projection: 'EPSG:4326', // 坐标系
          // center: [100.990969, 36.635013], // 地图中心点
          center: [-122.12828, 47.63963]
        }),
        //加载控件到地图容器中
        controls: defaultControls({
          zoom: false,
          rotate: false,
          attribution: false
        }),
      });

    },

    // 获取后台数据
    getMap() {
      // 获取点位数据
      KeyObject().then((res) => {
        if (res.code === 200) {
          // console.log('KeyObject', res);
          this.resPdata = res.data
          this.drawTyphoonPath();
          this.designClickOnMap()
          // console.log('this.resPdata', this.resPdata);
        }
      })
    },

    // 显示点
    drawTyphoonPath() {
      let data = []
      for (var i = 0; i < this.resPdata.length; i++) {
        if (this.resPdata[i] && this.resPdata[i].longitude && this.resPdata[i].latitude) {
          data.push({ longitude: this.resPdata[i].longitude, latitude: this.resPdata[i].latitude, id: this.resPdata[i].id })
        }
      }

      let points = data;
      let features = [];
      // console.log('points', points);

      for (let i = 0; i < data.length; i++) {
        let position = [points[i].longitude, points[i].latitude];

        let positionArr = fromLonLat(position)
        // console.log('positionArr', positionArr);

        if (!isNaN(positionArr[0]) && !isNaN(positionArr[1])) {
          let featurePoint = new Feature({
            geometry: new Point(positionArr),
          });

          featurePoint.setStyle(
            new Style({
              image: new Circle({
                fill: new Fill({
                  color: "#6159ff",
                }),
                radius: 6,
              }),
            })
          );

          // console.log('@@points', points[i]);
          featurePoint.set('pointData', points[i])
          features.push(featurePoint);
        }
      }
      // 矢量图层
      let layer = new VectorLayer();
      // 矢量数据源
      let source = new VectorSource({
        wrapX: false
      });
      source.addFeatures(features);
      layer.setSource(source);
      this.map.addLayer(layer);
    },

    // 注册一个click事件
    designClickOnMap: function () {
      let _this = this;
      this.map.on("click", function (ev) {
        let pixel = ev.pixel;
        let width = pixel[0] / _this.$store.state.switch.scaleS;
        let height = pixel[1] / _this.$store.state.switch.scaleS;
        let pix = [width, height]
        // console.log(pix)
        let feature = _this.map.forEachFeatureAtPixel(
          pix,
          function (feature) {
            return feature;
          }
        );
        if (feature) {
          // console.log(`output->feature.get('typhoonPoint')`, feature.get('pointData'))
          // console.log(`output->`, feature.values_.pointData.id)
          _this.getipData(feature);
        } else {
          // console.log("no feature");
          _this.$store.state.switch.showDetail = false;
          _this.$store.state.switch.showDetailTwo = false;
        }
      });
    },

    async getipData(feature) {
      let params = {
        id: feature.values_.pointData.id
      }

      if (this.$store.state.switch.showDetailTwo) {
        // 如果右侧详情页已展开，则先关闭详情页
        this.$store.state.switch.showDetailTwo = false;
        this.$store.state.rightDetails.socData = []; // 清空数据
      }

      let res = await KeyObjectDetails(params)
      if (res.code === 200) {
        // console.log('res', res);
        this.$store.state.rightDetails.socData = res.data
        this.$store.state.rightDetails.Rid = feature.values_.pointData.id //获取详情页id
      }
      this.$store.state.switch.showDetailTwo = true; //控制右侧详情页展开
    },
  },
};
</script>

<style lang="scss" scoped>
.map {
  width: 100%;
  height: 100%;
}
</style>
